package com.demo.bookstore.filter;

import com.demo.bookstore.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ddone
 * @date 2024/3/16-20:07
 */
@WebFilter({"/cart/*","/order/*"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        User user = (User) req.getSession().getAttribute("book_user");
        if(user == null){
           // 未登录 重定向到登录页面
           resp.sendRedirect(req.getContextPath()+"/user?method=toLogin");
        }else {
            // 登录过 放行
            chain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
